Masthead

JavaScript and Form Elements

What makes the Web truly powerful is the ability to use JavaScript to interact with DOM elements, including form elements.

Form Elements

First, create a basic web page with a "head" and "body" section. Then, add a form element as below:

Degrees: <input id="Degrees" type="text">

The formatting is not important for now as you'll have time to create a great looking web page. The name of this tag is "input" which is for basic form elements including text entry and buttons. The "type" identifies this form element as a "text" entry box.. The "id" identifies this specific HTML element and allows JavaScript to access it. Refresh the page and you should see a form element appear. Add additional form elements for "Minutes", "Seconds" and "DD" for decimal degrees.

Now create a button. The "value" will appear as text on the button. The "onclick" is the name of a JavaScript function we'll create in a second.

<input type="button" value="DMS to DD" onclick="DMSToDD()">

Now we'll create a JavaScript function that will be called when the button is clicked on. The "script" tags below enclose the JavaScript function. All JavaScript functions should appear in the "head" or heading block for now.

<script>
/*
* A function to convert DMS to DD
*/
function DMSToDD()
{
   console.log("DMSToDD function called");
}
</script>

Refresh your page and click the button. An alert should popup - welcome to JavaScript programming on the Web!

The next step is to "get" our elements, read values from them, and then put the value into another form element. We can "get" any DOM element in an HTML page with the getElementById(...) function in the "document" object. Then, we can set the value in the form element as below.

function DMSToDD()
{
   var DegreesElement=document.getElementById("Degrees");
   var DegreesValue=DegreesElement.value;

   var DDElement=document.getElementById("DD");
   DDElement.value=DDValue;
}

Your task is now to add the code that converts DMS to DD. Note that the values coming form the form elements are always strings of characters.

© Copyright 2018 HSU - All rights reserved.